// wx.request({
//   url: 'http://www.baidu.com',
//   method: "POST",
//   data: {},
//   header: "",
//   dataType: {},
//   responseType: {},
//   success(){},
//   fail(){},
//   complete(){}
// })

var config = require('config.js')
var api = require('extendApi.js')
/***
 * 封装请求方法
 * 所有的请求都需要做用户是否登录的判断: login 字段
 */
function request(params, isGetToken) {
  api.toast({
    title: '正在请求中',
  })
  wx.request({
    url: config.domain + params.url, //接口请求地址
    data: params.data,
    header: {
      'token': wx.getStorageSync('token')
    },
    method: params.method == undefined ? "POST" : params.method,
    dataType: 'json',
    responseType: params.responseType == undefined ? 'text' : params.responseType,
    success: function (res) {
      const responseData = res.data
      console.log('请求', config.domain + params.url, params.data, wx.getStorageSync('token'), responseData)
      const token = responseData.message
      if ((params.url == '/user/register' || params.url == '/user/login') && responseData.code == 200 && token !== 'OK') {
        wx.setStorageSync('token', token)
      }
      params.callBack(responseData.data);
    },
    fail: function (err) {
      wx.hideLoading();
      wx.showToast({
        title: "服务器出了点小差",
        icon: "none"
      });
    }
  })


}

/***获取购物车的数量 */
function getCartCount() {
  var params = {
    url: config.prodCountUrl,
    method: 'GET',
    data: {},
    callBack(res) {
      if (res > 0) {
        wx.setTabBarBadge({
          index: 2,
          text: res + "",
        })

        var app = getApp()
        app.globalData.totalCartCount = res;


      } else {
        wx.removeTabBarBadge({
          index: 2,
        })
        var app = getApp()
        app.globalData.totalCartCount = 0;
      }
    },
    errCallBack(res) {}
  }

  request(params)
}





exports.request = request;
exports.getCartCount = getCartCount;